﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataAccess
{
    public class BookService
    {
        private static readonly BookService m_BookService = new BookService();
        private DataAccess.BooksContext Ctx
        {
            get
            {
                return new BooksContext();
            }
        }

        public static BookService Instance
        {
            get { return m_BookService; }
        }

        /// <summary>
        /// 通过ID找书本
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Books.Models.Book GetBookByID(int id)
        {
            using (var db = this.Ctx)
            {
                var item = db.Books.FirstOrDefault(c => c.BookId == id);

                return item;
            }
        }


        /// <summary>
        /// 通过ID删除书本
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteBook(int id)
        {
            using (var db = this.Ctx)
            {
                var item = db.Books.FirstOrDefault(c => c.BookId == id);
                if (item != null)
                {
                    db.Books.Remove(item);
                    db.SaveChanges();
                }

                return false;
            }
        }


        /// <summary>
        /// 新增书本
        /// </summary>
        /// <param name="book"></param>
        /// <returns></returns>
        public bool AddBook(Books.Models.Book book)
        {
            using (var db = this.Ctx)
            {
                book.BookId = 0;
                book.ChangedTime = DateTime.Now;

                db.Books.Add(book);
                db.SaveChanges();

                return true;
            }
        }


        /// <summary>
        /// 更新书本信息
        /// </summary>
        /// <param name="book"></param>
        /// <returns></returns>
        public bool UpdateBook(Books.Models.Book book)
        {
            using (var db = this.Ctx)
            {
                var item = db.Books.FirstOrDefault(c => c.BookId == book.BookId);
                if (item != null)
                {
                    item.Name = book.Name;
                    item.Author = book.Author;
                    item.Publisher = book.Publisher;
                    item.Summary = book.Summary;
                    item.ChangedTime = DateTime.Now;

                    db.SaveChanges();
                    return true;
                }

                return false;
            }
        }


    }
}
